package com.pool.auth;

import android.content.SharedPreferences;

import com.pool.net.SpreadsheetsConnector;


/**
 * Methods related to authentication.
 *
 * TODO(claveld): See if we can use AccountManager.get(context).
 * @author claveld@gmail.com (David Clavel)
 */
public class Auth {

  private static final String AUTHKEY = "authkey";
  
  private static Auth instance = null;
  
  private final SharedPreferences sharedPreferences;
  private final SpreadsheetsConnector connector;
  
  public static void init(SharedPreferences sharedPreferences, SpreadsheetsConnector connector) {
    if (instance == null) {
      instance = new Auth(sharedPreferences, connector);
    }
  }
  
  public static Auth get() {
    if (instance == null) {
      throw new UnsupportedOperationException("Call Auth.init() before");
    }
    return instance;
  }
  
  private Auth(SharedPreferences sharedPreferences, SpreadsheetsConnector connector) {
    this.sharedPreferences = sharedPreferences;
    this.connector = connector;
  }
  
  public String authenticate(String email, String password) {
    String authKey = connector.authenticate(email, password);
    if (authKey != null) {
      SharedPreferences.Editor editor = sharedPreferences.edit();
      editor.putString(Auth.AUTHKEY, authKey);
      editor.commit();  
    }
    return authKey;
  }
  
  public String getAuthKey() {
    if (!isAlreadyLogged()) {
      throw new UnsupportedOperationException("User is not logged.");
    }
    return sharedPreferences.getString(Auth.AUTHKEY, null);
  }
  
  public boolean isAlreadyLogged() {
    return sharedPreferences.contains(Auth.AUTHKEY);
  }
  
  public void clearAuthData() {
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.clear();
    editor.commit();
  }
}
